<template>
  <s-layout>
    <view class="container">
      <view class="form-container">
        <!-- Header -->
        <view class="header-box">
          <text
            class="cicon-edit"
            style="color: #0052d9; font-size: 44rpx; margin-right: 20rpx"
          ></text>
          <text class="title">{{ formData.id ? "编辑" : "新增" }}企业档案</text>
        </view>

        <!-- Basic Info Card -->
        <view class="form-card">
          <fui-section
            title="基本信息"
            line-width="3px"
            line-color="#0052d9"
            isLine
            size="34"
            style="
              padding: 0;
              --fui-section-title-color: #1a1a1a;
              margin-bottom: 30rpx;
            "
          ></fui-section>

          <!-- File Name Input -->
          <fui-input
            label="文件名称："
            placeholder="请输入文件名称"
            v-model="formData.title"
            required
            style="
              --fui-input-label-color: #4f4e4e;
              --fui-input-color: #1a1a1a;
              margin-bottom: 40rpx;
            "
          >
            <text
              class="cicon-title"
              slot="prefix"
              style="color: #0052d9; font-size: 40rpx"
            ></text>
          </fui-input>

          <!-- 附件区域 - 现代美观设计 -->
          <view class="attachments-section">
            <view class="section-header">
              <view class="section-title-wrapper">
                <text class="section-title">附件</text>
                <text v-if="formData.files.length === 0" class="required-mark"
                  >*</text
                >
              </view>
              <view class="upload-stats">
                <view
                  class="stat-item"
                  :class="{ 'limit-reached': isImageLimitReached }"
                >
                  <fui-icon
                    name="picture"
                    :color="isImageLimitReached ? '#c0c4cc' : '#0052d9'"
                    :size="20"
                  ></fui-icon>
                  <text>{{ imageFiles.length }}/{{ maxImageCount }}</text>
                </view>
                <view
                  class="stat-item"
                  :class="{ 'limit-reached': isFileLimitReached }"
                >
                  <fui-icon
                    name="order"
                    :color="isFileLimitReached ? '#c0c4cc' : '#0052d9'"
                    :size="20"
                  ></fui-icon>
                  <text>{{ documentFiles.length }}/{{ maxFileCount }}</text>
                </view>
                <view
                  class="stat-item"
                  :class="{ 'limit-reached': isVideoLimitReached }"
                >
                  <fui-icon
                    name="video"
                    :color="isVideoLimitReached ? '#c0c4cc' : '#0052d9'"
                    :size="20"
                  ></fui-icon>
                  <text>{{ videoFiles.length }}/{{ maxVideoCount }}</text>
                </view>
                <view
                  class="stat-item"
                  :class="{ 'limit-reached': isTotalLimitReached }"
                >
                  <fui-icon
                    name="formfill"
                    :color="isTotalLimitReached ? '#c0c4cc' : '#0052d9'"
                    :size="20"
                  ></fui-icon>
                  <text>{{ formData.files.length }}/{{ maxTotalFiles }}</text>
                </view>
              </view>
            </view>

            <!-- 上传按钮区域 - 更现代的设计 -->
            <view class="upload-triggers-modern">
              <view
                class="trigger-btn"
                @click="handleChooseImage"
                :class="{ disabled: isImageLimitReached }"
              >
                <view class="btn-icon">
                  <fui-icon
                    name="picture"
                    :color="isImageLimitReached ? '#c8c9cc' : '#0052d9'"
                    :size="28"
                  ></fui-icon>
                </view>
                <text
                  class="btn-text"
                  :class="{ 'disabled-text': isImageLimitReached }"
                  >上传图片</text
                >
              </view>
              <view
                class="trigger-btn"
                @click="handleChooseFile"
                :class="{ disabled: isFileLimitReached }"
              >
                <view class="btn-icon">
                  <fui-icon
                    name="order"
                    :color="isFileLimitReached ? '#c8c9cc' : '#0052d9'"
                    :size="28"
                  ></fui-icon>
                </view>
                <text
                  class="btn-text"
                  :class="{ 'disabled-text': isFileLimitReached }"
                  >上传文件</text
                >
              </view>
              <view
                class="trigger-btn"
                @click="handleChooseVideo"
                :class="{ disabled: isVideoLimitReached }"
              >
                <view class="btn-icon">
                  <fui-icon
                    name="video"
                    :color="isVideoLimitReached ? '#c8c9cc' : '#0052d9'"
                    :size="28"
                  ></fui-icon>
                </view>
                <text
                  class="btn-text"
                  :class="{ 'disabled-text': isVideoLimitReached }"
                  >上传视频</text
                >
              </view>
            </view>

            <!-- 空态展示 - 更美观 -->
            <view v-if="!hasAnyFiles" class="empty-attachments-modern">
              <view class="empty-icon">
                <fui-icon name="upload" color="#c0c4cc" size="64"></fui-icon>
              </view>
              <text class="empty-text">暂无附件，请点击上方按钮上传</text>
            </view>

            <!-- 文件展示区域 - 更美观的设计 -->
            <view v-if="hasAnyFiles" class="files-showcase">
              <!-- 图片文件展示区 -->
              <view v-if="imageFiles.length > 0" class="file-type-section">
                <view class="type-header">
                  <view class="type-title">
                    <fui-icon
                      name="picture"
                      color="#0052d9"
                      :size="20"
                    ></fui-icon>
                    <text>图片 ({{ imageFiles.length }})</text>
                  </view>
                  <view
                    class="type-action"
                    @tap="handleChooseImage"
                    v-if="!isImageLimitReached"
                  >
                    <fui-icon name="plus" color="#0052d9" :size="20"></fui-icon>
                    <text>添加</text>
                  </view>
                </view>
                <view class="file-grid">
                  <view
                    v-for="(file, index) in imageFiles"
                    :key="file.id"
                    class="file-item image-item"
                  >
                    <image
                      :src="file.fileUrl"
                      mode="aspectFill"
                      class="file-preview"
                      @tap="
                        previewImage(
                          file.fileUrl,
                          imageFiles.map((f) => f.fileUrl)
                        )
                      "
                    />
                    <view class="file-badge">图片</view>
                    <view
                      class="delete-icon"
                      @tap.stop="handleDeleteMedia(file.id, 'image')"
                    >
                      <fui-icon name="close" :size="20" color="#fff"></fui-icon>
                    </view>
                  </view>
                </view>
              </view>

              <!-- 文档文件展示区 -->
              <view v-if="documentFiles.length > 0" class="file-type-section">
                <view class="type-header">
                  <view class="type-title">
                    <fui-icon
                      name="order"
                      color="#0052d9"
                      :size="20"
                    ></fui-icon>
                    <text>文件 ({{ documentFiles.length }})</text>
                  </view>
                  <view
                    class="type-action"
                    @tap="handleChooseFile"
                    v-if="!isFileLimitReached"
                  >
                    <fui-icon name="plus" color="#0052d9" :size="20"></fui-icon>
                    <text>添加</text>
                  </view>
                </view>
                <view class="document-list">
                  <view
                    v-for="(file, index) in documentFiles"
                    :key="file.id"
                    class="document-item"
                  >
                    <view
                      class="doc-preview"
                      @tap="previewFile(file.fileUrl, file.originalName)"
                    >
                      <view class="doc-icon">
                        <image
                          :src="file.fileUrl"
                          class="file-icon"
                          mode="aspectFit"
                        />
                      </view>
                      <view class="doc-info">
                        <text class="doc-name">{{ file.originalName }}</text>
                        <text class="doc-type">{{
                          getFileTypeLabel(file.originalName)
                        }}</text>
                      </view>
                      <view class="preview-btn">
                        <fui-icon
                          name="eye"
                          color="#0052d9"
                          :size="20"
                        ></fui-icon>
                      </view>
                    </view>
                    <view
                      class="delete-btn"
                      @tap.stop="handleDeleteFile(file.id, index)"
                    >
                      <fui-icon
                        name="close"
                        color="#ff4d4f"
                        :size="20"
                      ></fui-icon>
                    </view>
                  </view>
                </view>
              </view>

              <!-- 视频文件展示区 -->
              <view v-if="videoFiles.length > 0" class="file-type-section">
                <view class="type-header">
                  <view class="type-title">
                    <fui-icon
                      name="video"
                      color="#0052d9"
                      :size="20"
                    ></fui-icon>
                    <text>视频 ({{ videoFiles.length }})</text>
                  </view>
                  <view
                    class="type-action"
                    @tap="handleChooseVideo"
                    v-if="!isVideoLimitReached"
                  >
                    <fui-icon name="plus" color="#0052d9" :size="20"></fui-icon>
                    <text>添加</text>
                  </view>
                </view>
                <view class="file-grid">
                  <view
                    v-for="(file, index) in videoFiles"
                    :key="file.id"
                    class="file-item video-item"
                  >
                    <view class="file-preview video">
                      <fui-upload-video
                        immediate
                        :fileList="file.fileUrl?.split(',')"
                        isView
                        background="#ECF5FF"
                        addColor="#d1d1d1"
                        :width="195"
                        :height="195"
                      >
                      </fui-upload-video>
                      
                      
                    </view>
                    <view class="file-badge video-badge">视频</view>
                    <view
                      class="delete-icon"
                      @tap.stop="handleDeleteMedia(file.id, 'video')"
                    >
                      <fui-icon name="close" :size="20" color="#fff"></fui-icon>
                    </view>
                    <view class="video-duration">{{
                      getDurationLabel(index)
                    }}</view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-btn-container">
        <view class="submit-btn" @click="handleSubmit">
          <text class="btn-text">提交企业档案</text>
        </view>
      </view>
    </view>
  </s-layout>
</template>

<script setup >
import { ref, computed, nextTick } from "vue";
import sheep from "@/sheep";
import { onLoad } from "@dcloudio/uni-app";
import other from "@/sheep/api/other";

// Assuming fui-upload is registered globally or imported locally if needed
// import fuiUpload from '@/components/firstui/fui-upload/fui-upload.vue';

// --- Constants ---
const hostUrl = "https://assess.yuejin-tech.com"; // Ensure no trailing slash
const imageUploadUrl = `${hostUrl}/app_api.php?t=upload&op=image_upload&role=company&type=archival`;
const fileUploadUrl = `${hostUrl}/app_api.php?t=upload&op=image_upload&role=company&type=archival`;
const videoUploadUrl = `${hostUrl}/app_api.php?t=upload&op=image_upload&role=company&type=archival`;

// Use publicly accessible and reliable icon URLs
const pdfIconUrl =
  "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_acrobat.png";
const wordIconUrl =
  "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_word.png";
const genericFileIconUrl =
  "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white.png";
const excelIconUrl =
  "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_excel.png";
const pptIconUrl =
  "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_powerpoint.png";

// Optional: Default poster image for videos
const defaultVideoPoster =
  "https://via.placeholder.com/195x195/ECF5FF/808080?text=Video";

// 上传文件数量限制
const maxImageCount = ref(1); // 最大图片数量
const maxFileCount = ref(1); // 最大文件数量
const maxVideoCount = ref(1); // 最大视频数量
const maxTotalFiles = ref(1); // 最大附件总数量

// --- Reactive State ---
const formData = ref({
  id: null,
  title: "",
  item_id: null,
  company_id: null,
  files: [], // 存储所有上传的文件
});

// 按类型分组的文件集合
const imageFiles = computed(() => {
  return formData.value.files.filter((file) => file.fileType === "image");
});

const videoFiles = computed(() => {
  return formData.value.files.filter((file) => file.fileType === "video");
});

const documentFiles = computed(() => {
  return formData.value.files.filter((file) => file.fileType === "file");
});

// 检查是否达到上传限制
const isImageLimitReached = computed(() => {
  return (
    imageFiles.value.length >= maxImageCount.value || isTotalLimitReached.value
  );
});

const isFileLimitReached = computed(() => {
  return (
    documentFiles.value.length >= maxFileCount.value ||
    isTotalLimitReached.value
  );
});

const isVideoLimitReached = computed(() => {
  return (
    videoFiles.value.length >= maxVideoCount.value || isTotalLimitReached.value
  );
});

// 检查总数限制
const isTotalLimitReached = computed(() => {
  return formData.value.files.length >= maxTotalFiles.value;
});

// 判断是否有任何文件
const hasAnyFiles = computed(() => {
  return formData.value.files.length > 0;
});

// --- Helper Functions ---
// 生成唯一ID
const generateUniqueId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substring(2);
};

// 根据文件扩展名获取对应的图标
const getFileIconByExt = (filename) => {
  const lowerCaseName = filename.toLowerCase();
  if (lowerCaseName.endsWith(".pdf")) return pdfIconUrl;
  else if (lowerCaseName.endsWith(".doc") || lowerCaseName.endsWith(".docx"))
    return wordIconUrl;
  else if (lowerCaseName.endsWith(".xls") || lowerCaseName.endsWith(".xlsx"))
    return excelIconUrl;
  else if (lowerCaseName.endsWith(".ppt") || lowerCaseName.endsWith(".pptx"))
    return pptIconUrl;
  else return genericFileIconUrl;
};

// 获取简短文件名（如果过长）
const getShortenedFileName = (filename, maxLength = 10) => {
  if (filename.length <= maxLength) return filename;

  const ext =
    filename.lastIndexOf(".") > 0
      ? filename.substring(filename.lastIndexOf("."))
      : "";
  const nameWithoutExt = filename.substring(
    0,
    filename.lastIndexOf(".") > 0 ? filename.lastIndexOf(".") : filename.length
  );

  if (ext.length >= maxLength - 3) {
    return `...${ext}`;
  }

  const availableChars = maxLength - 3 - ext.length;
  return `${nameWithoutExt.substring(0, availableChars)}...${ext}`;
};



// 预览图片
const previewImage = (url, urls) => {
  uni.previewImage({
    current: url,
    urls: urls,
    fail: (err) => {
      console.error("预览图片失败:", err);
      uni.showToast({ title: "预览图片失败", icon: "none" });
    },
  });
};



// 预览文件
const previewFile = (url, name) => {
  // 对于PDF等可以预览的文件
  uni.downloadFile({
    url: url,
    success: (res) => {
      if (res.statusCode === 200) {
        const tempFilePath = res.tempFilePath;
        uni.openDocument({
          filePath: tempFilePath,
          fail: (err) => {
            console.error("打开文件失败:", err);
            uni.showToast({ title: "此文件类型无法在线预览", icon: "none" });
          },
        });
      }
    },
    fail: (err) => {
      console.error("下载文件失败:", err);
      uni.showToast({ title: "下载文件失败", icon: "none" });
    },
  });
};

// Function to decide which upload to trigger if placeholder is clicked
const triggerDefaultUpload = () => {
  handleChooseImage(); // Default to image selection
};

// --- Delete Logic ---
const handleDelete = (fileId) => {
  const fileIndex = formData.value.files.findIndex(
    (file) => file.id === fileId
  );
  if (fileIndex !== -1) {
    formData.value.files.splice(fileIndex, 1);
    uni.showToast({ title: "已移除", icon: "none" });
  }
};

// 专门处理文件删除，增加确认对话框
const handleDeleteFile = (fileId, index) => {
  uni.showModal({
    title: "提示",
    content: "确定要删除此文件吗？",
    success: (res) => {
      if (res.confirm) {
        handleDelete(fileId);
      }
    },
  });
};

// 处理图片和视频删除
const handleDeleteMedia = (fileId, type) => {
  const typeText = type === "image" ? "图片" : "视频";
  uni.showModal({
    title: "提示",
    content: `确定要删除此${typeText}吗？`,
    success: (res) => {
      if (res.confirm) {
        handleDelete(fileId);
      }
    },
  });
};

// --- Upload Logic ---
const handleChooseImage = () => {
  if (isTotalLimitReached.value) {
    uni.showToast({
      title: `最多只能上传${maxTotalFiles.value}个附件`,
      icon: "none",
    });
    return;
  }

  if (isImageLimitReached.value) {
    uni.showToast({
      title: `最多只能上传${maxImageCount.value}张图片`,
      icon: "none",
    });
    return;
  }
  chooseAndUploadImage();
};

const chooseAndUploadImage = () => {
  // 计算还能选择的图片数量
  const remainingTypeCount = maxImageCount.value - imageFiles.value.length;
  const remainingTotalCount = maxTotalFiles.value - formData.value.files.length;
  const remainingCount = Math.min(remainingTypeCount, remainingTotalCount);

  uni.chooseImage({
    count: remainingCount,
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    success: (res) => {
      if (!res.tempFilePaths || res.tempFilePaths.length === 0) {
        console.error("选择图片结果无效:", res);
        uni.showToast({ title: "选择图片失败", icon: "none" });
        return;
      }

      // 处理每一个选择的图片
      // 使用 Array.from 将 tempFilePaths 转换为数组再使用 forEach
      Array.from(res.tempFilePaths).forEach((tempFilePath, index) => {
        const file = res.tempFiles?.[index];
        const tempFileName =
          file?.name ||
          `image_${Date.now()}_${index}.${
            tempFilePath.split(".").pop() || "jpg"
          }`;
        uploadToServer(tempFilePath, imageUploadUrl, "image", tempFileName);
      });
    },
    fail: handleChooseFail("图片"),
  });
};

const handleChooseFile = () => {
  if (isTotalLimitReached.value) {
    uni.showToast({
      title: `最多只能上传${maxTotalFiles.value}个附件`,
      icon: "none",
    });
    return;
  }

  if (isFileLimitReached.value) {
    uni.showToast({
      title: `最多只能上传${maxFileCount.value}个文件`,
      icon: "none",
    });
    return;
  }
  chooseAndUploadFile();
};

const chooseAndUploadFile = () => {
  // 计算还能选择的文件数量
  const remainingTypeCount = maxFileCount.value - documentFiles.value.length;
  const remainingTotalCount = maxTotalFiles.value - formData.value.files.length;
  const remainingCount = Math.min(remainingTypeCount, remainingTotalCount);

  const chooseFunc = (type) => {
    const successCallback = (res) => {
      if (!res.tempFiles || res.tempFiles.length === 0) {
        console.error("选择文件结果无效:", res);
        uni.showToast({ title: "选择文件失败", icon: "none" });
        return;
      }

      // 处理每一个选择的文件（最多处理remainingCount个）
      const filesToProcess = res.tempFiles.slice(0, remainingCount);
      filesToProcess.forEach((file) => {
        if (
          !file ||
          !file.path ||
          typeof file.path !== "string" ||
          !file.name ||
          typeof file.name !== "string"
        ) {
          console.error(`选择的文件信息不完整:`, file);
          uni.showToast({ title: "文件信息不完整", icon: "none" });
          return;
        }
        uploadToServer(file.path, fileUploadUrl, "file", file.name);
      });

      // 如果选择的文件超过了限制
      if (res.tempFiles.length > remainingCount) {
        uni.showToast({
          title: `已达到最大文件数限制，仅上传了${remainingCount}个文件`,
          icon: "none",
          duration: 3000,
        });
      }
    };

    // 平台兼容处理
    // #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ
    uni.chooseMessageFile({
      count: remainingCount,
      type: "all",
      success: successCallback,
      fail: handleChooseFail("文件"),
    });
    // #endif
    // #ifdef H5 || APP-PLUS
    uni.chooseFile({
      count: remainingCount,
      type: "all",
      success: successCallback,
      fail: handleChooseFail("文件"),
    });
    // #endif
    // #ifndef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ || H5 || APP-PLUS
    console.warn(
      "uni.chooseFile/chooseMessageFile not available on this platform, using default chooseFile"
    );
    uni.chooseFile({
      count: remainingCount,
      type: "all",
      success: successCallback,
      fail: handleChooseFail("文件"),
    });
    // #endif
  };
  chooseFunc("all");
};

const handleChooseVideo = () => {
  if (isTotalLimitReached.value) {
    uni.showToast({
      title: `最多只能上传${maxTotalFiles.value}个附件`,
      icon: "none",
    });
    return;
  }

  if (isVideoLimitReached.value) {
    uni.showToast({
      title: `最多只能上传${maxVideoCount.value}个视频`,
      icon: "none",
    });
    return;
  }
  chooseAndUploadVideo();
};

const chooseAndUploadVideo = () => {
  // 视频通常一次只能选择一个
  uni.chooseVideo({
    sourceType: ["album", "camera"],
    compressed: true,
    maxDuration: 60,
    success: (res) => {
      if (!res || !res.tempFilePath || typeof res.tempFilePath !== "string") {
        console.error("选择视频结果无效:", res);
        uni.showToast({ title: "选择视频信息不完整", icon: "none" });
        return;
      }
      const tempFilePath = res.tempFilePath;
      const tempFileName =
        res.name ||
        `video_${Date.now()}.${tempFilePath.split(".").pop() || "mp4"}`;
      uploadToServer(tempFilePath, videoUploadUrl, "video", tempFileName);
    },
    fail: handleChooseFail("视频"),
  });
};

// Generic choose fail handler
const handleChooseFail = (type) => (err) => {
  console.log(`选择${type}失败:`, err);
  const isCancel =
    err.errMsg &&
    (err.errMsg.includes("cancel") || err.errMsg.includes("fail cancel"));
  if (!isCancel) {
    uni.showToast({ title: `选择${type}失败`, icon: "none" });
  } else {
    console.log(`用户取消选择${type}`);
  }
};

// Generic upload function
const uploadToServer = (
  tempFilePath,
  url,
  type,
  originalName
) => {
  console.log(`准备上传 ${type}:`, { tempFilePath, url, originalName });
  uni.showLoading({ title: "上传中...", mask: true });

  uni.uploadFile({
    url: url,
    filePath: tempFilePath,
    name: "file",
    formData: { original_name: originalName },
    success: (uploadRes) => {
      console.log(
        `上传 ${type} - 服务器原始响应 (status ${uploadRes.statusCode}):`,
        uploadRes.data
      );
      if (uploadRes.statusCode === 200) {
        let resData = null;
        try {
          const resDataStr = uploadRes.data.replace(/^\ufeff/, "");
          if (!resDataStr) {
            console.error(`上传 ${type} - 服务器响应为空`);
            uni.showToast({ title: "服务器响应为空", icon: "none" });
            return;
          }
          resData = JSON.parse(resDataStr);
          console.log(`上传 ${type} - 解析后的服务器数据:`, resData);

          if (
            resData.data &&
            (resData.code == 200 || resData.success === true)
          ) {
            const relativePathFromServer = resData.data;
            console.log(`上传 ${type} - 获取相对路径:`, relativePathFromServer);

            if (typeof relativePathFromServer !== "string") {
              console.error(
                `[Upload Error] 服务器返回了非字符串路径:`,
                relativePathFromServer,
                "Type:",
                typeof relativePathFromServer
              );
              uni.showToast({
                title: "服务器返回路径格式错误",
                icon: "none",
                duration: 3000,
              });
              return;
            }

            if (!relativePathFromServer.trim()) {
              console.error(`[Upload Error] 服务器返回了空路径`);
              uni.showToast({
                title: "服务器返回路径无效",
                icon: "none",
                duration: 3000,
              });
              return;
            }

            // URL构建
            let displayUrl = "";
            if (
              relativePathFromServer.startsWith("http://") ||
              relativePathFromServer.startsWith("https://")
            ) {
              displayUrl = relativePathFromServer; // 服务器提供的是绝对URL
            } else {
              // 从主机和相对路径构建
              const cleanedHost = hostUrl.endsWith("/")
                ? hostUrl.slice(0, -1)
                : hostUrl;
              const cleanedPath = relativePathFromServer.startsWith("/")
                ? relativePathFromServer.substring(1)
                : relativePathFromServer;
              displayUrl = `${cleanedHost}/${cleanedPath}`;
            }
            console.log(`上传 ${type} - 生成的最终显示 URL: ${displayUrl}`);

            // 确定最终显示URL（图标或实际URL）
            let finalDisplayUrl = "";
            if (type === "file") {
              finalDisplayUrl = getFileIconByExt(originalName);
              console.log(`文件类型，使用图标: ${finalDisplayUrl}`);
            } else {
              finalDisplayUrl = displayUrl; // 图片/视频使用构建的URL
              console.log(`${type} 类型，使用URL: ${finalDisplayUrl}`);
            }

            // 创建新的文件项并添加到集合中
            const newFile = {
              id: generateUniqueId(),
              filePath: relativePathFromServer,
              fileUrl: finalDisplayUrl,
              fileType: type,
              originalName: originalName,
              displayName: getShortenedFileName(originalName),
            };

            formData.value.files.push(newFile);
            uni.showToast({ title: "上传成功!", icon: "success" });
          } else {
            console.error("API 返回错误或数据格式不符:", resData);
            const errorMsg =
              resData.msg || resData.message || "上传失败: 服务器处理错误";
            uni.showToast({ title: errorMsg, icon: "none", duration: 3000 });
          }
        } catch (e) {
          console.error(
            `处理响应 JSON 或执行逻辑时出错 (Type: ${type}):`,
            e,
            "原始数据:",
            uploadRes.data
          );
          uni.showToast({ title: "处理服务器响应失败", icon: "none" });
        }
      } else {
        console.error(
          `上传 ${type} - HTTP 错误:`,
          uploadRes.statusCode,
          "数据:",
          uploadRes.data
        );
        uni.showToast({
          title: `上传失败: ${uploadRes.statusCode}`,
          icon: "none",
        });
      }
    },
    fail: (err) => {
      console.error(`上传 ${type} - 网络/请求错误:`, err);
      let errorTitle = "上传请求失败";
      if (err.errMsg && err.errMsg.toLowerCase().includes("timeout")) {
        errorTitle = "上传超时，请检查网络";
      }
      uni.showToast({ title: errorTitle, icon: "none" });
    },
    complete: () => {
      uni.hideLoading();
      console.log(
        `上传 ${type} - 操作完成. 当前文件列表:`,
        JSON.parse(JSON.stringify(formData.value.files))
      );
    },
  });
};

// --- Form Validation & Submission ---
const validateForm = () => {
  if (!formData.value.title.trim()) {
    uni.showToast({ title: "请填写文件名称", icon: "none" });
    return false;
  }

  // 检查是否有任何文件上传
  if (formData.value.files.length === 0) {
    uni.showToast({ title: "请至少上传一个附件", icon: "none" });
    return false;
  }

  return true;
};

const handleSubmit = async () => {
  if (!validateForm()) return;
  uni.showLoading({ title: "提交中...", mask: true });

  try {
    // 将文件数据转换为API所需的格式
    // 这里根据接口需求可能需要调整
    const dataToSend = {
      item_id: formData.value.item_id,
      tpc_id: formData.value.company_id,
      pca_title: formData.value.title,
      pca_type: formData.value.files[0].fileType,
      pca_url: formData.value.files[0].filePath.replace(
        /^https?:\/\/[^\/]+/,
        ""
      ), // 发送文件数组
    };

    if (formData.value.id) {
      dataToSend.id = formData.value.id;
    }

    console.log("Submitting data:", dataToSend);

    // 使用sheep.$api.qy_index.addDetail接口
    const res = await sheep.$api.other.addDetail(dataToSend);

    console.log("Submit Responseaa:", res);

    if (res.code == 200) {
      uni.showToast({
        title: res.msg || "提交成功!",
        icon: "success",
        duration: 1500,
      });
      setTimeout(() => {
        const pages = getCurrentPages();
        if (pages.length > 1) {
          sheep.$router.back();
        } else {
          sheep.$router.go("/pages/index/index");
        }
      }, 1500);
    } else {
      uni.showToast({
        title: res.msg || "提交失败",
        icon: "none",
        duration: 3000,
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error("Submit Error:", error);
    const errorMsg =
      error instanceof Error ? error.message : "提交时发生未知错误";
    uni.showToast({
      title: `提交出错: ${errorMsg}`,
      icon: "none",
      duration: 3000,
    });
  }
};

// --- Lifecycle ---
onLoad((options) => {
  console.log("onLoad options:", options);

  // 重置表单状态
  formData.value = {
    id: null,
    title: "",
    item_id: null,
    company_id: null,
    files: [],
  };

  console.log("onLoad formData:", formData.value);

  // 存储 item_id 和 company_id 到本地
  if (options?.item_id) {
    formData.value.item_id = options.item_id;
  }
  if (options?.company_id) {
    formData.value.company_id = options.company_id;
  }

  if (options?.id) {
    const id = parseInt(options.id, 10);
    if (!isNaN(id)) {
      formData.value.id = id;
      console.log("Editing mode, ID:", id);
      // TODO: Implement fetchRecordData(id);
    } else {
      console.warn("Invalid ID passed in options:", options.id);
    }
  } else {
    console.log("Creating new record.");
  }
});

// 获取文件类型标签
const getFileTypeLabel = (filename) => {
  const lowerCaseName = filename.toLowerCase();
  if (lowerCaseName.endsWith(".pdf")) return "PDF文档";
  else if (lowerCaseName.endsWith(".doc") || lowerCaseName.endsWith(".docx"))
    return "Word文档";
  else if (lowerCaseName.endsWith(".xls") || lowerCaseName.endsWith(".xlsx"))
    return "Excel表格";
  else if (lowerCaseName.endsWith(".ppt") || lowerCaseName.endsWith(".pptx"))
    return "PPT演示文稿";
  else if (lowerCaseName.endsWith(".txt")) return "文本文件";
  else if (lowerCaseName.endsWith(".zip") || lowerCaseName.endsWith(".rar"))
    return "压缩文件";
  else return "未知文件类型";
};

// 获取视频时长显示（示例）
const getDurationLabel = (index) => {
  // 这里只是示例，实际项目中应该从视频元数据中获取真实时长
  // 由于获取时长需要视频加载完成，可能需要额外处理
  const mockDurations = ["01:25", "03:42", "00:58", "02:17", "05:03"];
  return mockDurations[index % mockDurations.length];
};
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  background-color: #f8f9fa;
  min-height: 100vh;
  box-sizing: border-box;
}

.header-box {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  .title {
    font-size: 40rpx;
    font-weight: 700;
    color: #1a1a1a;
  }
}

.form-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx 24rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 82, 217, 0.08);
}

// 附件区域
.attachments-section {
  margin-bottom: 40rpx;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24rpx;
  padding-bottom: 16rpx;
  border-bottom: 1px solid #f0f2f5;
}

.section-title-wrapper {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.section-title {
  font-size: 32rpx;
  color: #303133;
  font-weight: 500;
}

.required-mark {
  color: #ff4d4f;
  margin-left: 4rpx;
  font-size: 32rpx;
}

.upload-stats {
  display: flex;
  align-items: center;
  gap: 16rpx;
  background: #f9f9f9;
  padding: 10rpx 16rpx;
  border-radius: 8rpx;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6rpx;

  text {
    font-size: 24rpx;
    color: #606266;
  }

  &.limit-reached {
    text {
      color: #c0c4cc;
    }
  }
}

.upload-triggers-modern {
  display: flex;
  justify-content: space-between;
  margin: 30rpx 0;
  padding: 20rpx;
  background: #f7f8fa;
  border-radius: 12rpx;
}

.trigger-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  padding: 20rpx 0;
  border-radius: 8rpx;
  transition: all 0.3s;

  .btn-icon {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #ecf5ff;
    border-radius: 50%;
    margin-bottom: 8rpx;
  }

  .btn-text {
    font-size: 26rpx;
    color: #303133;
    font-weight: 500;
  }

  &:hover:not(.disabled) {
    background-color: #f0f7ff;
    transform: translateY(-2rpx);

    .btn-icon {
      background: #d8e8ff;
    }
  }

  &.disabled {
    cursor: not-allowed;
    opacity: 0.6;

    .disabled-text {
      color: #c0c4cc;
    }
  }
}

.empty-attachments-modern {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 60rpx 0;
  padding: 60rpx 0;
  background: #f9f9f9;
  border-radius: 8rpx;
  border: 1px dashed #dcdfe6;

  .empty-icon {
    margin-bottom: 20rpx;
  }

  .empty-text {
    font-size: 28rpx;
    color: #909399;
    text-align: center;
  }
}

.files-showcase {
  margin-top: 30rpx;
}

.file-type-section {
  width: 100%;
  margin-bottom: 40rpx;
  background: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.type-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.type-title {
  display: flex;
  align-items: center;
  gap: 8rpx;

  text {
    font-size: 28rpx;
    color: #303133;
    font-weight: 500;
  }
}

.type-action {
  display: flex;
  align-items: center;
  gap: 4rpx;
  background: #ecf5ff;
  padding: 6rpx 12rpx;
  border-radius: 6rpx;
  cursor: pointer;

  text {
    font-size: 24rpx;
    color: #0052d9;
  }

  &:hover {
    background: #d8e8ff;
  }
}

.file-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  padding: 20rpx;
}

.file-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
  overflow: hidden;
  background-color: #f5f7fa;
  border: 1px solid #ebeef5;
  transition: transform 0.3s, box-shadow 0.3s;

  &:hover {
    transform: translateY(-4rpx);
    box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.1);
  }
}

.image-item {
  .file-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.file-badge {
  position: absolute;
  top: 8rpx;
  left: 8rpx;
  background-color: #0052d9;
  color: #fff;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
  font-size: 22rpx;
  z-index: 1;
}

.video-badge {
  background-color: #ff4d4f;
}

.delete-icon {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 36rpx;
  height: 36rpx;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
  cursor: pointer;
  transition: background-color 0.2s;

  &:hover {
    background-color: rgba(0, 0, 0, 0.8);
  }
}

.play-icon-modern {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60rpx;
  height: 60rpx;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1;
}

.video-duration {
  position: absolute;
  bottom: 8rpx;
  right: 8rpx;
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
  font-size: 22rpx;
  z-index: 1;
}

.document-list {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.document-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx;
  border: 1px solid #ebeef5;
  border-radius: 8rpx;
  background: #fff;
  cursor: pointer;
  transition: background-color 0.2s, transform 0.2s;

  &:hover {
    background-color: #f5f7fa;
    transform: translateY(-2rpx);
  }
}

.doc-preview {
  display: flex;
  align-items: center;
  flex: 1;
}

.doc-icon {
  width: 48rpx;
  height: 48rpx;
  margin-right: 16rpx;

  .file-icon {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}

.doc-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4rpx;
  overflow: hidden;
  margin-right: 16rpx;
}

.doc-name {
  font-size: 26rpx;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.doc-type {
  font-size: 22rpx;
  color: #909399;
}

.preview-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  margin-right: 8rpx;

  &:hover {
    background-color: #ecf5ff;
  }
}

.delete-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  padding: 6rpx;
  background-color: #f8f8f8;

  &:hover {
    background-color: #fff0f0;
  }
}

// Submit Button Styling
.submit-btn-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx calc(20rpx + env(safe-area-inset-bottom));
  background-color: #f8f9fa;
  z-index: 10;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.submit-btn {
  background: linear-gradient(135deg, #0052d9, #2979ff);
  border-radius: 50rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 16rpx rgba(0, 82, 217, 0.3);
  transition: background 0.3s ease, transform 0.2s;

  &:active {
    background: linear-gradient(
      135deg,
      darken(#0052d9, 5%),
      darken(#2979ff, 5%)
    );
    transform: scale(0.98);
  }

  .btn-text {
    color: #fff;
    font-size: 32rpx;
    font-weight: 500;
  }
}
</style>
